package logic

import (
	"center-data-platform/app/notice/internal/svc"
	"center-data-platform/app/notice/model"
	"center-data-platform/app/notice/notice"
	"context"
	"database/sql"
	"errors"
	"fmt"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendLogic {
	return &SendLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SendLogic) Send(in *notice.NoticeReq) (*notice.NoticeResp, error) {
	if len(in.UserId) < 1 {
		return nil, errors.New("invalid user id")
	}
	for _, userId := range in.UserId {
		_, err := l.svcCtx.NoticeModel.Insert(l.ctx, &model.Systemnotifications{
			UserId: sql.NullInt64{
				Int64: userId,
				Valid: true,
			},
			Content: sql.NullString{
				String: in.Content,
				Valid:  true,
			},
			CreatedTime: time.Now(),
			UpdatedTime: time.Now(),
		})
		if err != nil {
			logx.Error(fmt.Sprintf("发送系统消息失败，接收人id：%d,错误信息：%s", userId, err.Error()))
			continue
		}
	}

	return &notice.NoticeResp{
		Code: 200,
		Msg:  "发送成功",
	}, nil

}
